package com.meituan.verintreport.task;

import com.meituan.verintreport.db.dao.FormComponentsMapper;
import com.meituan.verintreport.db.dto.FormComponentsDto;
import com.meituan.verintreport.db.verint.VerintBaseTableDao;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 全量同步
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "base-table.form-components")
public class BaseTableTaskFormComponents extends BaseTableTask {
    @Resource
    private FormComponentsMapper formComponentsMapper;

    @Resource
    private VerintBaseTableDao verintBaseTableDao;

    @Value("${base-table.form-components.maxMinutesPerTime}")
    private int maxMinutesPerTime = 15;

    /**
     * 全量同步 每天12：20
     */
    @Scheduled(cron = "${base-table.form-components.cron}")
    public void execute() {
        if (!isEnable()) {
            return;
        }

       // long startTime = System.currentTimeMillis();

        Integer rs = formComponentsMapper.removeFormComponentsAll();
        log.info("remove {} data", rs);
        int pageIndex = 0;
        int pageSize = 1000;
        boolean shouldContinue;
        do {
            shouldContinue = false;

            //Integer maxId = formComponentsMapper.getMaxId();
           // log.info("last max id: {}", maxId);

           // List<FormComponentsDto> records = verintBaseTableDao.getFormComponentsList(maxId);
            List<FormComponentsDto> records = verintBaseTableDao.getFormComponentsListByPage(pageIndex,pageSize);
            log.info("got {} records", records.size());
            if (records.size() == 1000) {
                shouldContinue = true;
            }

            for (FormComponentsDto record : records) {
                try {
                    formComponentsMapper.insert(record);
                } catch (Exception ex) {
                    log.error("Add record to db exception.", ex);
                }
            }
            pageIndex += pageSize;


            // long endTime = System.currentTimeMillis();
            // if (endTime - startTime > maxMinutesPerTime * 60 * 1000) {
            //     shouldContinue = false;
            // }
        }
        while (shouldContinue);
    }
}
